@section('content')
<div class="am-g m-cart">
	<div class="am-u-md-12">
		<div class="m-cart-hd am-cf">
			<h1>确认订单</h1>
			<!-- 
			<span class="free-tip">订单满500元免运费</span>
			 -->
		</div>
	</div>
	<form method="post" action="{{URL::to('order')}}" id="order-form"  name="order-form">
	<div class="am-u-md-12 m-order-fragment">
		<h3>送货地址</h3>
		<div class='m-order-addresses'>
			@if (!empty($addresses))
			@foreach($addresses as $adrs)
			<div class="am-radio m-order-address"  data-id='{{$adrs->id}}' data-mobile='{{$adrs->mobile}}' data-name='{{$adrs->name}}' 
				data-zipcode='{{$adrs->zipcode}}' data-street='{{$adrs->street}}'
				data-province_id='{{$adrs->province_id}}' data-city_id='{{$adrs->city_id}}' data-district_id='{{$adrs->district_id}}'>
				<input type="radio" name="user_address_id" value="{{$adrs->id}}">
				<span class="m-order-address-content">
					{{$adrs->name}}, {{$adrs->province}} {{$adrs->city.$adrs->district.$adrs->street}}, <span class='mobile'>{{$adrs->mobile}}</span>
					<a href="javascript:void(0)" class="update">修改地址</a>
				</span>
			</div>
			@endforeach
			@endif
		</div>
		<p>
		<button class="m-btn m-btn-normal" id="add-address-btn" type="button">使用新地址</button>
		</p>
	</div>
	
	<div class="am-u-md-12 m-order-fragment">
		<h3>礼物卡片选项</h3>
		<div class="am-radio"><label><input type="radio" name="card_type" value="1" checked="checked">我不需要卡片</label></div>
		<div class="am-radio"><label><input type="radio" name="card_type" value="2">我需要一张空白卡片</label></div>
		<div class="am-radio"><label><input type="radio" name="card_type" value="3">请为我代写一张卡片</label></div>
		<div class="am-form-group" style="display: none" id="card-content-box">
			<div class="am-cf m-horizontal-group">
		      <textarea id="card_content" name='card_content' placeholder="我们可为您代写卡片，请在此输入卡片内容，字数限制为100字"></textarea>
		      <span class="m-field-error"></span> 
			</div>
		</div>
	</div>
	<div class="am-u-md-12 m-order-fragment">
		<h3>如有特殊要求请在此留言</h3>
		<div class="am-form-group">
			<div class="am-cf m-horizontal-group">
		      <textarea id="leave_message" name='leave_message' placeholder="字数限制为100字"></textarea>
		      <span class="m-field-error"></span> 
			</div>
		</div>
	</div>
	<div class="am-u-md-12 m-cart-table-box">
		<div class="m-cart-loading"><span class='am-icon-spinner am-icon-spin'></span></div>
	</div>
	
	<div class="am-u-md-12 ">
		
		<div class="m-cart-back">
			<!-- 
			<a href="javascript:history.go(-1);"><i class="am-icon-angle-double-left"></i> 继续购物</a>
			 -->
		</div>
		
		<div class="m-cart-stat">
			<div>小计:<span class="subtal-value"></span></div>
			<div class="freight">运费:<span class="freight-value"></span></div>
			<div class="total">总计:<span class="total-value"></span></div>
		</div>
	</div>
	
	
    <div class="am-u-md-12 ">
    	<div class="m-cart-pay-btn-box">
    	<button type="submit" class="m-btn" id="order-submit-btn"  data-am-loading="{spinner: 'circle-o-notch', loadingText: '提交中...'}">提交订单</button>
    	</div>
    </div>
    {{Form::token()}}
    </form>
    @if(!empty($recommends))
	<div class="am-u-md-12 am-cf">
	<div class="m-recommends">
		<p class="am-margin-top am-margin-bottom">您可能喜欢以下商品</p>
		<div class="am-g ">
		 @foreach($recommends as $p)
		  <div class="m-recommend">
		  	 <a href="{{URL::to('product',$p->id)}}" title="{{$p->name}}">
		      <img src="{{Images::url($p->image,200,240)}}" alt="{{$p->name}}"/>
		      <div>
		        <div class="brand">{{$p->brand}}</div>
		        <div>{{$p->name}}</div>
		      </div>
		    </a>
		  </div>
		@endforeach
		</div>
	</div>
	</div>
	@endif
</div>

@stop

@section('script')
<script type="text/x-handlebars-template" id="cart-tpl">
<table class="am-table m-cart-table">
    <thead>
        <tr>
            <th>商品</th>
            <th>价格</th>
            <th>数量</th>
			<th>金额</th>
        </tr>
    </thead>
    <tbody>
		@{{#each this}}
        <tr data-id="@{{id}}" data-size_id="@{{size_id}}" data-color_id="@{{color_id}}" data-quantity="@{{quantity}}" data-price="@{{price}}">
            <td>
				<div class='m-cart-item am-cf'>
					<a href="@{{url 'product/' id}}"><img src='@{{imgurl image 72 72}}'></img><a>
			  		<div class='m-cart-item-bd'>
			  			<div class='name'>@{{enname}}</div>
			  			<div class='name'>@{{name}}</div>
						@{{#if size}}
                        <div class='name'>尺寸:@{{size}}</div>
						@{{/if}}
						@{{#if color}}
                        <div class='name'>颜色:@{{color}}</div>
						@{{/if}}
			  		</div>
				</div>
			</td>
            <td>¥ @{{fnumber price}}</td>
            <td><span class='quantity'>@{{quantity}}</span></td>
			<td>¥<span class='money'>@{{multi-fnumber price quantity}}<span></td>
        </tr>
		@{{/each}}
    </tbody>
</table>
</script>

<script type="text/x-handlebars-template" id="add-address-tpl">
<div class="m-login am-cf">
<h2>添加/修改地址</h2>
<div class="m-login-bd">
	<div class="m-register">
		<form class="am-form"  id="add-address-form" name="add-address-form" method="post" 
				action="{{URL::to('user/address/add')}}">
			<div class="am-form-group">
		      <label for="name">姓名<span class="m-required">*</span></label>
			  <div class="am-cf m-horizontal-group">
		      <input type="text" class="m-input validate" id="name" name="name" 
				data-rules="required|max_length[32]" data-display="姓名" placeholder="输入姓名">
			  <span class="m-field-error"></span>
              </div>
		    </div>
			<div class="am-form-group">
		      <label for="mobile">手机<span class="m-required">*</span></label>
		      <div class="am-cf m-horizontal-group">
			 <input type="text" class="m-input validate" id="mobile" name="mobile" 
				data-rules="required|mobile" data-display="手机号" placeholder="输入手机号">
			  <span class="m-field-error"></span>
			</div>
		    </div>
			<div class="am-form-group">
		      <label for="zipcode">邮政编码</label>
			  <div class="am-cf m-horizontal-group">
		      <input type="text" class="m-input validate" id="zipcode" name="zipcode" 
				data-rules="max_length[16]|alpha_numeric" data-display=邮政编码" placeholder="输入邮政编码">
			  <span class="m-field-error"></span>
              </div>
		    </div>
			<div class="am-form-group">
		      <label for="province_id">省/直辖市<span class="m-required">*</span></label>
		      <div class="am-cf m-horizontal-group">
			  <select id="province_id" name="province_id" class="m-input validate">
			  </select>
			  <span class="m-field-error"></span>
			 </div>
		    </div>
			<div class="am-form-group">
		      <label for="city_id">市<span class="m-required">*</span></label>
			 <div class="am-cf m-horizontal-group">
			  <select id="city_id" name="city_id" class="m-input validate">
			  </select>
              <span class="m-field-error"></span>
	          </div>
		    </div>
		    <div class="am-form-group">
		      <label for="district_id">区/县<span class="m-required">*</span></label>
			<div class="am-cf m-horizontal-group">
		      <select id="district_id" name="district_id" class="m-input validate">
			  </select>
              <span class="m-field-error"></span>
            </div>
		    </div>
			<div class="am-form-group">
		      <label for="street">详细地址<span class="m-required">*</span></label>
			  <div class="am-cf m-horizontal-group">
   			  <textarea  class="m-input validate" id="street" name="street"
				data-rules="required|max_length[256]" data-display="详细地址" placeholder="请输入详细地址"></textarea>
		      <span class="m-field-error"></span> 
			</div>
		    </div>
			{{Form::token()}}
		    <p><button type="submit" class="m-btn">保存</button></p>
		    <p class="m-form-error"></p>
		</form>
	</div>
</div>
</div>
</script>

<script type="text/x-handlebars-template" id="address-tpl">
<div class="am-radio m-order-address" data-id='@{{id}}' data-mobile='@{{mobile}}' data-name='@{{name}}' 
	data-zipcode='@{{zipcode}}' data-street='@{{street}}' 
	data-province_id='@{{province_id}}' data-city_id='@{{city_id}}' data-district_id='@{{district_id}}'>
	<input type="radio" name="user_address_id" value="@{{id}}"  checked='checked'>
	<span class="m-order-address-content active">
		@{{name}}, @{{province}} @{{city}}@{{district}}@{{street}}, <span class='mobile'>@{{mobile}}</span>
		<a href="javascript:void(0)" class="update">修改地址</a>
	</span>
</div>
</script>

<script type="text/x-handlebars-template" id="item-tpl">
@{{#each this}}
<option value="@{{id}}" data-id="@{{id}}">@{{name}}</option>
@{{/each}}
</script>

<script type="text/javascript">
$(function(){

	$("input[name='card_type']").on("click",function(){

		if ($(this).val() == 3){
			$("#card-content-box").show();
		} else {
			$("#card-content-box").hide();
		}
	});
	var tpl = $("#cart-tpl").text();
	var template = Handlebars.compile(tpl);
	var products = $.cart.list();
	$('.m-cart-table-box').html(template(products));

	function refreshCartStat(products){
		var subtotal = 0;
		var freeFreight = false;
		$.each(products,function(i,e){
			subtotal += e.quantity * e.price;
			if (e.postage_mode == 2){
				freeFreight = true;
			}
		});

		$(".subtal-value").text("¥ "+$.maoutil.formatNumber(subtotal));
		if (subtotal >= $.config.freePostageLimit){
			$(".freight-value").text("免运费");
			$(".total-value").text("¥ "+$.maoutil.formatNumber(subtotal));
		} else {
			if (freeFreight){
				$(".freight-value").text("免运费");
			} else {
				$(".freight-value").text("¥"+$.maoutil.formatNumber($.config.postage));
			}
			$(".total-value").text("¥ "+$.maoutil.formatNumber((subtotal+$.config.postage)));
		}
	}

	//刷新统计数据
	refreshCartStat(products);

	$(document).on("click","#add-address-btn",function(){
		$content = $($("#add-address-tpl").html());
		$.dialog.show({
				tpl:$content,
				events:{
					open:function(){
						fillProvinces();
						//增加表单验证
						initAddressForm();
					}
				}
			});
	});

	function initAddressForm(successFn){
		var $form = $("#add-address-form");
		var $submit = $form.find("button");
		var errorFn = function(errors){
			$form.find(".m-field-error").html("");
			if ($.isArray(errors)){
				  $.each(errors,function(i,e){
					  var $msg = $(e.element).next();
					  $msg.text(e.message);
				  });
			  } else {
				  for (var key in errors){
					  var $ele = $form.find("#"+key).next();
					  $ele.text(errors[key][0]);
				  }
			}
		}

		var successFn = successFn || function(data){
			$(".m-order-address-content").removeClass('active');
			var tpl = $("#address-tpl").text();
			var template = Handlebars.compile(tpl);
			$(".m-order-addresses").append(template(data));
			//$.boxer('close');
			$.dialog.close();
			//默认选中最后一个
		}
		$form.validate(function($form,errors,events){
			errorFn(errors);
		  });
		  var options = {
		            beforeSubmit:function(){
		            	$submit.button('loading');
		            },
		            success: function (data) {
		            	$submit.button('reset');
			            //成功
			            if (data.success){
			            	//刷新当前页面
			            	successFn(data);
			            } else {
			            	errorFn($form,data.errors);
				        }
		            }
		   };
		   $form .ajaxForm(options);
	}

	function initUpdateAddressForm(data){
		var $form = $("#add-address-form");
		$form.find("#name").val(data["name"]);
		$form.find("#mobile").val(data["mobile"]);
		$form.find("#zipcode").val(data["zipcode"]);
		$form.find("#province_id").val(data["province_id"]);
		$form.find("#city_id").val(data["city_id"]);
		$form.find("#district_id").val(data["district_id"]);
		$form.find("#street").text(data["street"]);
		$form.append("<input name='id' type='hidden' value='"+data.id+"'/>");
	}
	$(document).on('change','#province_id',function(){
		var $item = $('#province_id').find("option:selected");
		id = $item.data().id;
		$.get("{{URL::to('user/address/cities')}}/"+id,function(data){
			fillCities(data);
		});
	});

	
	$(document).on('change','#city_id',function(){
		var $item = $('#city_id').find("option:selected");
		id = $item.data().id;
		$.get("{{URL::to('user/address/districts')}}/"+id,function(data){
			fillDistricts(data);
		});
	});

	function fillProvinces(pid,cid,successFn){
		var params = "";
		if (pid){
			params = "?pid="+pid+"&cid="+cid;
		}
		$.get("{{URL::to('user/address/provinces')}}"+params,function(data){
			fillSelect($("#province_id"),data['provinces']);
			fillCities(data);
			if (successFn){
				successFn();
			}
		});
	}

	function fillCities(data){
		fillSelect($("#city_id"),data['cities']);
		fillDistricts(data['districts']);
	}

	function fillDistricts(data){
		fillSelect($("#district_id"),data);
	}

	function fillSelect($select,data){
		var tpl = $("#item-tpl").text();
		var template = Handlebars.compile(tpl);
		$select.html(template(data));
	}

	$(document).on("click","input[name='user_address_id']",function(){
		$(".m-order-address-content").removeClass('active');
		$("input[name='user_address_id']:checked").next().addClass('active');
	});

	$(document).on("click",".m-order-address .update",function(){
		//
		var $address = $(this).closest(".m-order-address").data();
		$content = $($("#add-address-tpl").html());
		$.dialog.show({
				tpl:$content,
				events:{
					open:function(){
						fillProvinces($address.province_id,$address.city_id,function(){
							//初始化修改数据
							initUpdateAddressForm($address);
						});
						
						//增加表单验证
						initAddressForm(function(data){
							//成功同步数据到dom
							var tpl = $("#address-tpl").text();
							var template = Handlebars.compile(tpl);
							$updateAddress = $(template(data));
							$address = $(".m-order-address[data-id='"+data.id+"']");
							$address.data(data);
							$address.html($updateAddress.html());
							$.dialog.close();
						});
					}
						
				}
			});
	});

	 var orderOptions = {
		beforeSubmit:function(){
			//1.验证是否有产品
			var list = $.cart.list();
			if (list.length == 0){
				var msgTpl = "<div class='m-favorite-success'><span>您的购物车里没有商品，请您选择购买的商品!</span><a href='{{URL::to('product-list')}}'><span class='m-go-favorite'>查看商品列表</span></a></div>";
				$.boxer($(msgTpl));
				return false;
			}
			//验证是否选择了地址
			if ($("input[name='user_address_id']:checked").length == 0){
				$(".m-order-addresses").css('border','1px solid red');
				window.scrollTo(0,0);
				return false;
			}

			//验证卡片内容
			var cardType = $("input[name='card_type']:checked").val();
			//需要购买卡片
			if (cardType == 3){
				var cardContent = $("#card_content").val();
				if (!(cardContent.length > 0 && cardContent.length <= 100)){
					$("#card_content").next().text("请填写卡片内容，并且卡片内容需要在100字内");
					return false;
				}
			}

			var leaveMessage = $("#leave_message").val();
			if (leaveMessage.length > 100){
				$("#leave_message").next().text("给卖家留言需要在100字内");
				return false;
			}
			$("#order-submit-btn").button("loading");
		},
		success:function(data){
			//成功需要清除产品cookie
			$("#order-submit-btn").button('reset');
            //成功
            if (data.success){
            	//删除商品cookie信息
            	$.cart.destroyAll();
            	window.location.href = $.config.base+"order/pay/"+data.order_id;
            } else {
            	alert("订单错误，可能库存不足!");
	        }
		}
	};
	$("#order-form") .ajaxForm(orderOptions);

});
</script>
@stop
